<template>
  <yc-container spacious>
    <yc-search-panel slot="header" v-model="active">
      <yc-bar slot="title">
        <yc-bar-space />
        <yc-bar-cell>
          <yc-pagination :full="false" @change="handlePageChange" :pagination="pagination" />
        </yc-bar-cell>
        <yc-bar-space />
        <yc-bar-cell>
          <el-button-group>
            <yc-button size="mini" icon="el-icon-refresh" label="刷新" @click="handleFetchTableData" />
            <yc-button size="mini" icon="el-icon-set-up" label="设置" @click="handleSettingTable" />
          </el-button-group>
        </yc-bar-cell>
        <yc-bar-cell>
          <yc-button type="primary" size="mini" icon="el-icon-plus" label="新增" v-permission="['management:dict:add']"
            @click="handleDictCreate" />
        </yc-bar-cell>
      </yc-bar>
      <yc-form ref='form' v-model="search" :setting="formSetting" :itemSetting="formItemSetting" />
    </yc-search-panel>
    <yc-table height="100%" ref="table" :api="dictApi" :columns="columns" @toggle-row-expand="handleDictToggleRowExpand"
      auto-resize :pagination="pagination" highlight-current-row>
      <template v-slot:childTable="{ row }">
        <yc-table :ref="`detailTable${row.id}`" :mode="2" :paging="false" :api="dictDetailApi"
          :customQueryIndex="customDictDetailsQuery" :columns="detailColumns" highlight-current-row>
          <template v-slot:dialogOperation="{ row  }">
            <yc-button type="text" size="mini" label="编辑" v-permission="['management:dict:update']"
              @click="handleDictDetailUpdate(row)" />
            <yc-button size="mini" type="text" label="删除" v-permission="['management:dict:delete']"
              @click="handleDeleteItemRow(row)" />
          </template>
        </yc-table>
      </template>
      <template v-slot:type="{ row  }">
        <span v-if="row.type === 1">
          数字
        </span>
        <span v-if="row.type === 2">
          字符串
        </span>
      </template>
      <template v-slot:moreOperation="{ row,rowIndex  }">
        <yc-button type="text" size="mini" label="编辑" v-permission="['management:dict:update']"
          @click="handleDictUpdate(row)" />
        <yc-button size="mini" type="text" label="删除" v-permission="['management:dict:delete']"
          @click="$refs.table.handleDeleteRow(row)" />
        <el-dropdown size="mini" trigger="click" @command="handleMoreCommand">
          <span class="el-dropdown-link">
            更多<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-permission="['management:dict:update']"
              :command="beforeHandleCommand(rowIndex, row,'a')">新增子级</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </yc-table>
    <yc-bar slot="footer">
      <yc-bar-cell>
        <yc-button type="primary" size="mini" icon="el-icon-tickets" label="全选" @click="handleAllSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document-copy" label="反选" @click="handleInvertSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document" label="全不选" @click="handleAllNoneSelection" />
        <yc-button type="danger" size="mini" icon="el-icon-delete" label="删除" v-permission="['management:dict:delete']"
          @click="handleDeleteTable" />
      </yc-bar-cell>
      <yc-bar-space />
      <yc-bar-cell>
        <vxe-pager size="mini" @page-change="handlePageChange" :page-sizes="[25, 50, 100, 150]"
          :current-page="pagination.current" :page-size="pagination.size" :total="pagination.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']">
        </vxe-pager>
      </yc-bar-cell>
    </yc-bar>
    <yc-dialog width="600px" :mode="mode" :conf="dialogConf" @on-submit="handleDictSubmit">
      <yc-form ref="dictForm" v-model="dictFormData" :setting="dictFormSetting" :itemSetting="dictFormItemSetting" />
    </yc-dialog>
    <yc-dialog width="600px" :mode="mode" :conf="dictDetailDialogConf" @on-submit="handleDictDetailSubmit">
      <yc-form ref="dictDetailForm" v-model="dictDetailFormData" :setting="dictDetailFormSetting"
        :itemSetting="dictDetailFormItemSetting" />
    </yc-dialog>
  </yc-container>
</template>

<script>
import { queryDicts, addDict, updateDict, removeDict, queryDictDetailsByName } from '@api/management/dict'
import { queryDictDetails, addDictDetail, updateDictDetail, removeDictDetail } from '@api/management/dict-detail'
import crud from '@/mixins/crud'
export default {
  name: 'dict',
  mixins: [crud],
  data () {
    return {
      dictApi: {
        index: queryDicts,
        del: removeDict
      },
      dictDetailApi: {
        index: queryDictDetails,
        del: removeDictDetail
      },
      dialogConf: {
        dialogVisible: false
      },
      dictDetailDialogConf: {
        dialogVisible: false
      },
      mode: 'create',
      dictFormData: {},
      dictDetailFormData: {},
      formSetting: {
        useLayout: false,
        inline: true,
        size: 'mini',
        labelPosition: 'top'
      },
      formItemSetting: [
        {
          prop: 'name',
          default: '',
          title: '名称',
          col: { span: 6 },
          name: 'input',
          clearable: true,
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'status',
          default: '',
          title: '状态',
          col: { span: 6 },
          name: 'dict-select',
          dictName: 'normal_status',
          visible: true
        },
        {
          title: '操作',
          visible: true,
          name: 'button-group',
          options: [
            {
              label: '搜索',
              type: 'primary',
              click: () => { this.handleFetchTableData() }
            },
            {
              label: '重置',
              click: () => { this.handleRestTableData() }
            }
          ]
        }
      ],
      dictFormSetting: {
        useLayout: true,
        inline: false,
        size: 'mini',
        labelPosition: 'right',
        labelWidth: '150px'
      },
      dictFormItemSetting: [
        {
          prop: 'name',
          default: '',
          title: '字典名称',
          col: { span: 18 },
          name: 'input',
          rule: { required: true, message: '请输入字典名称', trigger: 'change' },
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'description',
          default: '',
          title: '描述',
          col: { span: 18 },
          name: 'input',
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'type',
          default: '',
          title: '类型',
          col: { span: 18 },
          name: 'dict-select',
          visible: true,
          placeholder: '请输入内容',
          customDict: true,
          all: false,
          options: [
            { label: '数字', value: 1 },
            { label: '字符串', value: 2 },
            { label: '布尔值', value: 3 }
          ]
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 18 },
          name: 'radio-group',
          visible: true,
          options: [
            { label: '正常', value: 1 },
            { label: '停用', value: 0 }
          ]
        }
      ],
      dictDetailFormSetting: {
        useLayout: true,
        inline: false,
        size: 'mini',
        labelPosition: 'right',
        labelWidth: '150px'
      },
      dictDetailFormItemSetting: [
        {
          prop: 'label',
          default: '',
          title: 'label',
          col: { span: 18 },
          name: 'input',
          rule: { required: true, message: '请输入名称', trigger: 'change' },
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'value',
          default: '',
          title: '值',
          col: { span: 18 },
          name: 'input',
          rule: { required: true, message: '请输入值', trigger: 'change' },
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 18 },
          name: 'radio-group',
          visible: true,
          options: [
            { label: '正常', value: 1 },
            { label: '停用', value: 0 }
          ]
        }
      ],
      columns: [
        { key: 'checkbox', type: 'checkbox', width: '50' },
        { key: 'seq', type: 'seq', width: '50' },
        { key: 'expand', type: 'expand', width: '50', slots: { content: 'childTable' } },
        { key: 'name', field: 'name', title: '名称', formatter: 'formatEmpty', minWidth: '100' },
        { key: 'description', field: 'description', title: '描述', formatter: 'formatEmpty', minWidth: '100' },
        { key: 'type', field: 'type', title: '类型', slots: { default: 'type' }, minWidth: '100' },
        { key: 'createTime', field: 'createTime', title: '创建日期', minWidth: '150' },
        { key: 'status', field: 'status', title: '状态', width: '150', formatter: 'formatEmpty', cellRender: { name: 'ElSwitch', props: { activeColor: '#13ce66', inactiveColor: '#ff4949', activeValue: 1, inactiveValue: 0 }, events: { change: this.handleDictChange } } },
        { key: 'operation', title: '操作', width: '150', slots: { default: 'moreOperation' } }
      ],
      detailColumns: [
        { type: 'seq', width: '50' },
        { field: 'label', title: '名字', formatter: 'formatEmpty', minWidth: '150' },
        { field: 'value', title: '值', formatter: 'formatEmpty', minWidth: '100' },
        { field: 'createTime', title: '创建日期', minWidth: '150' },
        { field: 'status', title: '状态', width: '120', formatter: 'formatEmpty', cellRender: { name: 'ElSwitch', props: { activeColor: '#13ce66', inactiveColor: '#ff4949', activeValue: 1, inactiveValue: 0 }, events: { change: this.handleDictDetailChange } } },
        { key: 'operation', title: '操作', width: '120', slots: { default: 'dialogOperation' } }
      ],
      selectRow: null
    }
  },
  computed: {
  },
  created () {
  },
  mounted () {

  },
  methods: {
    handleDictCreate () {
      this.mode = 'create'
      this.dictFormData = {}
      this.dialogConf.dialogVisible = true
    },
    handleDictUpdate (row) {
      this.mode = 'update'
      this.selectRow = row
      this.dictFormData = this.$_.cloneDeep(row)
      this.dialogConf.dialogVisible = true
    },
    handleDictDetailCreate (selectRow) {
      this.mode = 'create'
      this.selectRow = selectRow
      this.dictDetailFormData = {}
      this.dictDetailDialogConf.dialogVisible = true
    },
    handleDictDetailUpdate (row) {
      this.mode = 'update'
      this.selectRow = row
      this.dictDetailFormData = this.$_.cloneDeep(row)
      this.dictDetailDialogConf.dialogVisible = true
    },
    handleDictSubmit (callBack) {
      var record = this.dictFormData
      if (this.mode === 'create') {
        addDict(record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('添加成功')
            this.$refs.table.insertRow(data, null, null)
          } else {
            this.$message.error('添加失败')
          }
          callBack(code === 200)
        })
      } else {
        updateDict(record.id, record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.$refs.table.updateRow(this.selectRow, data)
            this.selectRow = null
          } else {
            this.$message.error('修改失败')
          }
          callBack(code === 200)
        })
      }
    },
    handleDictDetailSubmit (callBack) {
      var record = this.dictDetailFormData
      if (this.selectRow === null) {
        this.$message.warning('请选择行')
        return
      }
      var tableName
      if (this.mode === 'create') {
        tableName = `detailTable${this.selectRow.id}`
        addDictDetail(this.selectRow.id, record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$refs[tableName].insertRow(data, null, null)
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
          callBack(code === 200)
        })
      } else {
        tableName = `detailTable${this.selectRow.dictId}`
        updateDictDetail(record.id, record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.$refs[tableName].updateRow(this.selectRow, data)
            this.selectRow = null
          } else {
            this.$message.error('修改失败')
          }
          callBack(code === 200)
        })
      }
    },
    dictDetailAddRow (detailTable, row) {
      if (detailTable) {
        let record = {
          dictId: row.id,
          status: 1
        }
        setTimeout(() => {
          detailTable.insertRow(record, 'labelZhCN', null)
        }, 500)
      }
    },
    hadnleDictSaveRow (row) {
      this.$refs.table.hadnleSaveRow(row)
    },
    hadnleDictCancelRow (row) {
      this.$refs.table.hadnleCancelRow(row)
    },
    handleDictEditRow (row) {
      this.$refs.table.setActiveRow(row)
    },
    beforeHandleCommand (rowIndex, row, command) {
      return {
        'rowIndex': rowIndex,
        'row': row,
        'command': command
      }
    },
    handleMoreCommand ({ rowIndex, row, command }) {
      switch (command) {
        case 'a':
          this.$refs.table.openRowExpand(row).then(() => {
            this.handleDictDetailCreate(row)
          })
          break
      }
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.pagination.current = currentPage
      this.pagination.size = pageSize
      this.handleFetchTableData()
    },
    handleDictChange ({ row }) {
      updateDict(row.id, row).then(res => {
        var { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
        } else {
          row.status = !row.status
          this.$message.error('修改失败')
        }
      })
    },
    handleDictDetailChange ({ row }) {
      updateDictDetail(row.id, row).then(res => {
        var { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
        } else {
          row.status = !row.status
          this.$message.error('修改失败')
        }
      })
    },
    customDictDetailsQuery () {
      var row = this.selectRow
      if (row) {
        return queryDictDetailsByName(row.name)
      }
    },
    handleDictToggleRowExpand ({ expanded, row }) {
      if (expanded) {
        this.selectRow = row
      }
    },
    handleDeleteItemRow (row) {
      var tableName = `detailTable${this.selectRow.id}`
      this.$refs[tableName].handleDeleteRow(row)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-container {
  background-color: white;
  width: 100%;
  height: 100%;
}
.el-aside {
  width: 300px !important;
  position: relative;
}
.container {
  ::v-deep.yc-container-full__body {
    padding: 0px 20px !important;
  }
}
.el-main {
  margin: 0px 20px;
  padding: 0px !important;
}
.el-dropdown {
  margin-left: 10px;
  font-size: 12px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon--right {
  margin-left: 1px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
